package model

import (
	"leeframe/internal/pkg/logger"
	"leeframe/internal/schema"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type User struct {
	ID         int
	Username   string
	UserStatus int
	CreatedAt  time.Time `gorm:"time"`
	UpdatedAt  time.Time `gorm:"time"`
}

// List
// @Author: lee
// @Date: 2021-11-29 16:42:48
// @Description: 获取用户列表
func (t *User) List(ctx *gin.Context, db *gorm.DB, pagination schema.Pagination) (listData []*User, err error) {
	offset := (pagination.Page - 1) * pagination.Size
	listData = make([]*User, pagination.Size)

	if err := db.Select("id,username").Offset(offset).Limit(pagination.Size).Order("id asc").Find(&listData).Error; err != nil {
		logger.ErrorN(ctx, "get user list err: ", err)
		return nil, err
	}

	return listData, err
}

// ListCount
// @Author: lee
// @Date: 2021-12-03 14:59:00
// @Description: 获取用户列表总数
func (t *User) ListCount(ctx *gin.Context, db *gorm.DB) (total int64, err error) {
	var count int64
	if err := db.Model(t).Count(&count).Error; err != nil {
		logger.ErrorN(ctx, "get user list count err: ", err)
		return 0, err
	}

	return count, nil
}

// Info
// @Author: lee
// @Date: 2021-11-30 11:29:00
// @Description: 获取用户信息
func (t *User) Info(ctx *gin.Context, db *gorm.DB, where string, args ...interface{}) (info *User, err error) {
	info = &User{}
	err = db.Select("id,username,created_at").Where(where, args...).First(&info).Error
	if err != nil {
		logger.ErrorN(ctx, "get user info err: ", err)
		return nil, err
	}
	return
}

// Create
// @Author: lee
// @Date: 2021-11-30 11:29:00
// @Description: 创建用户
func (t *User) Create(ctx *gin.Context, db *gorm.DB, username string) (id int, err error) {
	user := &User{}
	user.Username = username

	err = db.Create(&user).Error
	if err != nil {
		logger.ErrorN(ctx, "create user err: ", err)
		return 0, err
	}
	id = user.ID

	return
}

// Delete
// @Author: lee
// @Date: 2021-12-23 16:49:52
// @Description: 删除用户
func (t *User) Delete(ctx *gin.Context, db *gorm.DB, where string, args ...interface{}) error {
	user := &User{}
	if err := db.Where(where, args...).Delete(&user).Error; err != nil {
		logger.ErrorN(ctx, "delete user err: ", err)
		return err
	}
	return nil
}
